package com.bocloud.cmp.driver.providers.os;

import java.util.List;

import org.openstack4j.api.Builders;
import org.openstack4j.model.common.ActionResponse;
import org.openstack4j.model.network.Port;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bocloud.cmp.driver.convertor.BeanConvert;
import com.bocloud.cmp.driver.convertor.os.ConverPort;
import com.bocloud.cmp.driver.providers.PortDriver;
import com.bocloud.cmp.model.PortModel;
import com.bocloud.common.model.BsmResult;
import com.google.common.collect.Lists;

public class OSPortDriver extends OSDriver implements PortDriver {

	private static Logger logger = LoggerFactory.getLogger(OSPortDriver.class);

	public OSPortDriver() {
		super();
	}

	public OSPortDriver(String endpoint, String username, String password, String tenant, String domain, String project,
			Version version) {
		super(endpoint, username, password, tenant, domain, project, version);
	}

	@Override
	public BsmResult sync() {
		List<PortModel> models = Lists.newArrayList();
		List<? extends Port> ports = Lists.newArrayList();
		if (!this.accessable()) {
			logger.error(this.getError());
			return new BsmResult(false, this.getError());
		}
		ports = this.getClient().networking().port().list();
		if (null != ports) {
			BeanConvert<PortModel, Port> convertPort = new ConverPort();
			models = convertPort.convertList(ports);
		}
		return new BsmResult(true, models, "success");
	}

	@Override
	public BsmResult create(PortModel portModel) {
		String name = portModel.getName();
		String networkId = portModel.getNetworkId();
		if (!this.accessable()) {
			logger.error(this.getError());
			return new BsmResult(false, this.getError());
		}
		Port port = this.getClient().networking().port()
				.create(Builders.port().name(name).networkId(networkId).build());
		if (null != port) {
			BeanConvert<PortModel, Port> convertPort = new ConverPort();
			portModel = convertPort.convertModel(port);
		}
		return new BsmResult(true, portModel, "创建成功!");
	}

	@Override
	public BsmResult remove(String portId) {
		if (!this.accessable()) {
			logger.error(this.getError());
			return new BsmResult(false, this.getError());
		}
		ActionResponse response = this.getClient().networking().port().delete(portId);
		if (response.isSuccess()) {
			return new BsmResult(true, "端口删除成功！");
		} else {
			logger.error("remove port [{}] failed :{}", portId, response.getFault());
			return new BsmResult(false, "端口删除失败！");
		}
	}

	@Override
	public BsmResult detail(String portId) {
		if (!this.accessable()) {
			logger.error(this.getError());
			return new BsmResult(false, this.getError());
		}
		Port port = this.getClient().networking().port().get(portId);
		if (null != port) {
			BeanConvert<PortModel, Port> convertPort = new ConverPort();
			PortModel portModel = convertPort.convertModel(port);
			return new BsmResult(true, portModel, "查询成功!");
		} else {
			logger.error("get port error");
			return new BsmResult(false, "查询失败!");
		}
	}

}
